/*
 * ServicioForm.java
 *
 * Created on May 27, 2011, 3:02 PM
 */

package basededatos;
import javax.swing.*;
//import Forms.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.Dimension;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author  poweruser
 */
public class GestionCargas extends javax.swing.JFrame {

    /** Creates new form ServicioForm */
    public GestionCargas() {
        
        ConectBD();
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        MasterTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        idcarga = new javax.swing.JTextField();
        idcliente = new javax.swing.JTextField();
        idrack = new javax.swing.JTextField();
        fechasalida = new javax.swing.JTextField();
        boton_nuevo = new javax.swing.JButton();
        boton_eliminar = new javax.swing.JButton();
        boton_guardar = new javax.swing.JButton();
        boton_actualizar = new javax.swing.JButton();
        peso = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        estado = new javax.swing.JComboBox();
        movimiento = new javax.swing.JComboBox();
        tipo = new javax.swing.JComboBox();
        monto = new javax.swing.JTextField();
        dardebaja = new javax.swing.JButton();

        setTitle("Gestion de Cargas");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        JList list;
        ListSelectionModel listSelectionModel;
        DefaultTableModel modelo = new DefaultTableModel();
        listSelectionModel = MasterTable.getSelectionModel();
        listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
        MasterTable.setSelectionModel(listSelectionModel);
        MasterTable.setModel(modelo
        );
        try{
            java.sql.Statement inst = conexion.createStatement();
            String querry = "Select * from carga";
            ResultSet rs = inst.executeQuery(querry);
            //Obteniendo datos de la base de datos e ingresandolos a una Jtable
            //DefaultTableModel modelo = new DefaultTableModel();
            //JTable tabla = new JTable(modelo);
            ResultSetMetaData metaDatos = rs.getMetaData();
            int numColumnas = metaDatos.getColumnCount();
            Object[] etiquetas = new Object[numColumnas];
            for (int i = 0; i < numColumnas; i++) {
                etiquetas[i] = metaDatos.getColumnLabel(i + 1);
                //System.out.println(etiquetas[i]);
            }
            modelo.setColumnIdentifiers(etiquetas);
            while (rs.next()) {
                Object[] fila = new Object[numColumnas];
                for (int j = 0; j < numColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                }
                modelo.addRow(fila);
            }

            inst.execute("END");
            inst.close();
        }catch(Exception e){

        }
        MasterTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                MasterTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(MasterTable);

        jLabel1.setText("ID Carga:");

        jLabel2.setText("ID Cliente:");

        jLabel3.setText("ID Rack:");

        jLabel4.setText("Fecha de Salida (aaaa-mm-dd):");

        idcarga.setEditable(false);

        idcliente.setEditable(false);
        idcliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                idclienteActionPerformed(evt);
            }
        });

        idrack.setEditable(false);

        fechasalida.setEditable(false);
        fechasalida.setEnabled(false);

        boton_nuevo.setText("Nuevo");
        boton_nuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_nuevoActionPerformed(evt);
            }
        });

        boton_eliminar.setText("Eliminar");
        boton_eliminar.setEnabled(false);
        boton_eliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_eliminarActionPerformed(evt);
            }
        });

        boton_guardar.setText("Guardar");
        boton_guardar.setEnabled(false);
        boton_guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_guardarActionPerformed(evt);
            }
        });

        boton_actualizar.setText("Actualizar");
        boton_actualizar.setEnabled(false);
        boton_actualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_actualizarActionPerformed(evt);
            }
        });

        peso.setEditable(false);

        jLabel5.setText("Peso:");

        jLabel6.setText("Estado:");

        jLabel7.setText("Movimiento:");

        jLabel8.setText("Monto:");

        jLabel9.setText("Tipo Almacenaje:");

        estado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Activa", "Abandonada" }));
        estado.setEnabled(false);

        movimiento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Exportacion", "Importacion" }));
        movimiento.setEnabled(false);

        tipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Normal", "Refrigerada" }));
        tipo.setEnabled(false);

        monto.setEditable(false);

        dardebaja.setText("Dar de baja");
        dardebaja.setEnabled(false);
        dardebaja.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dardebajaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(idcarga, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(idcliente, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(idrack, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(estado, 0, 228, Short.MAX_VALUE)
                        .addGap(237, 237, 237))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tipo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(movimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(fechasalida))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(peso))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(monto, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(boton_nuevo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(boton_eliminar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(boton_guardar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(boton_actualizar)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dardebaja))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 492, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(idcarga, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2)
                        .addComponent(idcliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(idrack, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(fechasalida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(peso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(estado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(movimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(monto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boton_nuevo)
                    .addComponent(boton_eliminar)
                    .addComponent(boton_guardar)
                    .addComponent(boton_actualizar)
                    .addComponent(dardebaja))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


private void idclienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idclienteActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_idclienteActionPerformed

private void boton_nuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_nuevoActionPerformed
    boton_guardar.setEnabled(true);
    boton_actualizar.setEnabled(false);
    boton_eliminar.setEnabled(false);
    idcliente.setEditable(true);
    idrack.setEditable(true);
    //fechasalida.setEditable(true);
    peso.setEditable(true);
    monto.setEditable(true);
    movimiento.setEnabled(true);
    tipo.setEnabled(true);
    estado.setEnabled(true);
    dardebaja.setEnabled(false);
    

    
    idcarga.setText(null);
    idcliente.setText("");
    idrack.setText("");
    fechasalida.setText("");
    peso.setText("");
    monto.setText("");
    
    
}//GEN-LAST:event_boton_nuevoActionPerformed

private void MasterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MasterTableMouseClicked
    //boton_eliminar.setEnabled(false);
    //boton_guardar.setEnabled(false);
}//GEN-LAST:event_MasterTableMouseClicked

private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    CloseConection();
}//GEN-LAST:event_formWindowClosing

private void boton_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_guardarActionPerformed
    String Estado="", mov="", Tipo="";
    String IDCR = idcarga.getText();
    String IDCL = idcliente.getText();
    String IDR = idrack.getText();
    String FS= fechasalida.getText();
    String Peso=peso.getText();
    if(estado.getSelectedIndex()==0)
        Estado="true";
    if(estado.getSelectedIndex()==1)
        Estado="false";
    mov = movimiento.getSelectedItem().toString().toLowerCase();
    String Monto = monto.getText();
    if(tipo.getSelectedIndex()==0)
        Tipo="false";
    if(tipo.getSelectedIndex()==1)
        Tipo="true";
    if(!(fechasalida.getText().length()>0))
        FS=null;
    
         
    //System.out.println(tipo);
    try {
            java.sql.Statement inst = conexion.createStatement();
            //INSERT INTO cliente VALUES ($1, $2);
            String querry = "Select NuevaCarga("+IDCL+","+IDR+", cast("+Peso+" as numeric(2,0)),"
                    +Estado+",cast('"+mov+"'as varchar(11)), cast("+Monto+" as numeric(2,0)),"+Tipo+")";
            //System.out.println(querry);
            ResultSet rs = inst.executeQuery(querry);
            this.updateMasterTable();

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_boton_guardarActionPerformed

private void boton_actualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_actualizarActionPerformed
    String Estado="", mov="", Tipo="";
    String IDCR = idcarga.getText();
    String IDCL = idcliente.getText();
    String IDR = idrack.getText();
    String FS= fechasalida.getText();
    String Peso=peso.getText();
    if(estado.getSelectedIndex()==0)
        Estado="true";
    if(estado.getSelectedIndex()==1)
        Estado="false";
    mov = movimiento.getSelectedItem().toString().toLowerCase();
    String Monto = monto.getText();
    if(tipo.getSelectedIndex()==0)
        Tipo="false";
    if(tipo.getSelectedIndex()==1)
        Tipo="true";
    if(!(fechasalida.getText().length()>0))
        FS=null;
    try {
         
            java.sql.Statement inst = conexion.createStatement();
            inst.executeUpdate("UPDATE carga SET idcliente="+IDCL+", idrack="+IDR+", peso= cast("+Peso+" as numeric(2,0)), estado="
                    +Estado+", movimiento=cast('"+mov+"'as varchar(11)), montoc=cast("+Monto+" as numeric(2,0)), refrigerada="+Tipo+" WHERE idcarga="+IDCR);
            
            //INSERT INTO cliente VALUES ($1, $2);
            //String querry = "UPDATE Servicio SET idcarga="+carga+", montoservicio="+Monto
                  //  +", tipo='"+Tipo+"' WHERE idservicio="+servicio;
            //System.out.println(querry);
            //ResultSet rs = inst.executeQuery(querry);
            this.updateMasterTable();

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

}//GEN-LAST:event_boton_actualizarActionPerformed

private void boton_eliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_eliminarActionPerformed
    String ID = idcarga.getText();
    //System.out.println(ID);

    try {
            java.sql.Statement inst = conexion.createStatement();
            inst.executeUpdate("DELETE FROM carga WHERE idcarga="+ID);
           
            this.updateMasterTable();

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_boton_eliminarActionPerformed

private void dardebajaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dardebajaActionPerformed
    String ID = idcarga.getText();

    try {
            java.sql.Statement inst = conexion.createStatement();
            inst.executeUpdate("UPDATE carga set fechasalida=CURRENT_TIMESTAMP WHERE idcarga="+ID);
           
            this.updateMasterTable();

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_dardebajaActionPerformed

private static Connection conexion;
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                  new GestionCargas().setVisible(true);
            }
        });
    }
    
    public void CloseConection(){
        try {
            conexion.close();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void ConectBD(){
        String driver, user, pass, direccion;
                try {
                    driver = "org.postgresql.Driver";
                    user = ParseXML.user;
                    pass = ParseXML.passwd;
                    direccion = "jdbc:postgresql://localhost:5432/serbd/";

                    Class.forName(driver);
                    conexion = DriverManager.getConnection(direccion, user, pass);
                    //System.out.println("Se ha conectado exitosamente a la BD");
                    //new Main().setVisible(true);
                    
                    //SetClientComboBox();
                    //conexion.close();
                } catch (Exception e) {
                    System.out.println("No se pudo realizar la Conexion");
                    e.printStackTrace();
                }
    }
    
    
    public void updateMasterTable(){
        //System.out.println("Actualizando....");
        DefaultTableModel modelo = new DefaultTableModel();
        MasterTable.setModel(modelo);
        try {
            java.sql.Statement inst = conexion.createStatement();
            String querry = "Select * from carga";
            ResultSet rs = inst.executeQuery(querry);
            //Obteniendo datos de la base de datos e ingresandolos a una Jtable
            //DefaultTableModel modelo = new DefaultTableModel();
            //JTable tabla = new JTable(modelo);
            ResultSetMetaData metaDatos = rs.getMetaData();
            int numColumnas = metaDatos.getColumnCount();
            Object[] etiquetas = new Object[numColumnas];
            for (int i = 0; i < numColumnas; i++) {
                etiquetas[i] = metaDatos.getColumnLabel(i + 1);
                //System.out.println(etiquetas[i]);
            }
            modelo.setColumnIdentifiers(etiquetas);
            while (rs.next()) {
                Object[] fila = new Object[numColumnas];
                for (int j = 0; j < numColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                }
                modelo.addRow(fila);
            }

            inst.execute("END");
            inst.close();
        } catch (Exception e) {
        }
    }
    
    class SharedListSelectionHandler implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent e) { 
            ListSelectionModel lsm = (ListSelectionModel)e.getSource();
            try{
                int firstIndex = e.getFirstIndex();
                int lastIndex = e.getLastIndex();

                int fila=0;

                if (lsm.isSelectionEmpty()) {
                    //output.append(" <none>");
                } else {
                    // Find out which indexes are selected.
                    int minIndex = lsm.getMinSelectionIndex();
                    int maxIndex = lsm.getMaxSelectionIndex();
                    for (int i = minIndex; i <= maxIndex; i++) {
                        if (lsm.isSelectedIndex(i)) {
                            fila=i;
                           // System.out.println("FILA: " + i);
                        }
                    }
                }
                
                idcarga.setText(MasterTable.getValueAt(fila, 0)+"");
                idcliente.setText(MasterTable.getValueAt(fila, 1)+"");
                idrack.setText(MasterTable.getValueAt(fila, 2)+"");
                fechasalida.setText(MasterTable.getValueAt(fila, 4)+"");
                peso.setText(MasterTable.getValueAt(fila, 6)+"");
                monto.setText(MasterTable.getValueAt(fila, 9)+"");
                if((MasterTable.getValueAt(fila, 7)+"").equals("true"));
                    estado.setSelectedIndex(0);
                if((MasterTable.getValueAt(fila, 7)+"").equals("false"));
                    estado.setSelectedIndex(1);
                if((MasterTable.getValueAt(fila, 8)+"").equals("Exportacion"));
                    estado.setSelectedIndex(0);
                if((MasterTable.getValueAt(fila, 8)+"").equals("Importacion"));
                    estado.setSelectedIndex(1);
                if((MasterTable.getValueAt(fila, 10)+"").equals("true"));
                    estado.setSelectedIndex(1);
                if((MasterTable.getValueAt(fila, 10)+"").equals("false"));
                    estado.setSelectedIndex(0);
                    
                idcliente.setEditable(true);
                idrack.setEditable(true);
                //fechasalida.setEditable(true);
                peso.setEditable(true);
                fechasalida.setEditable(true);
                estado.setEnabled(true);
                movimiento.setEnabled(true);
                monto.setEditable(true);
                tipo.setEnabled(true);
                
                boton_guardar.setEnabled(false);
                boton_eliminar.setEnabled(true);
                boton_actualizar.setEnabled(true);
                dardebaja.setEnabled(true);
            }catch(Exception exe){
                //System.out.println("exception loca");
            }
            
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable MasterTable;
    private javax.swing.JButton boton_actualizar;
    private javax.swing.JButton boton_eliminar;
    private javax.swing.JButton boton_guardar;
    private javax.swing.JButton boton_nuevo;
    private javax.swing.JButton dardebaja;
    private javax.swing.JComboBox estado;
    private javax.swing.JTextField fechasalida;
    private javax.swing.JTextField idcarga;
    private javax.swing.JTextField idcliente;
    private javax.swing.JTextField idrack;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField monto;
    private javax.swing.JComboBox movimiento;
    private javax.swing.JTextField peso;
    private javax.swing.JComboBox tipo;
    // End of variables declaration//GEN-END:variables

}


